package com.vf.admin.client.controller;

import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dto.AppSpouseDto;
import com.vf.admin.client.service.*;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.miaodong.entity.AppGift;
import com.vf.admin.miaodong.entity.AppSpouseClerk;
import com.vf.admin.miaodong.entity.AppUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Random;

@Controller
@CrossOrigin
@RequestMapping("/app/spouseClerk")
public class AppSpouseClerkController extends ClientBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private AppSpouseClerkService appSpouseClerkService;
    @Autowired
    private AppGiftService appGiftService;
    @Autowired
    private AppGiftNumService appGiftNumService;
    @Autowired
    private AppAuthUserService appAuthUserService;

    /**
     * 夫妻相匹配
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/spouseMatch")
    public Result spouseMatch(HttpServletRequest request) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }
            Integer integer = appAuthUserService.infoByUserAndName(appUser.getId(), ClientConstants.UserAuth.REAL_AUTH);
            if (integer != 2) {
                return this.errorJSON("请进行真人认证");
            }
            Integer toUserId = 0;
            if (redisUtil.hasKey(RedisKeys.spouseMatch + appUser.getId())) {
                toUserId = (Integer) redisUtil.get(RedisKeys.spouseMatch + appUser.getId());
            } else {
                if (appUser.getSex() == 1) {
                    AppUser appUser1 = appUserService.randomMatchUser(2, appUser.getBiaoqianid(), appUser.getLon(), appUser.getLat());
                    if (appUser1 == null) {
                        return this.errorJSON("匹配失败");
                    }
                    toUserId = appUser1.getId();
                } else if (appUser.getSex() == 2) {
                    AppUser appUser1 = appUserService.randomMatchUser(1, appUser.getBiaoqianid(), appUser.getLon(), appUser.getLat());
                    if (appUser1 == null) {
                        return this.errorJSON("匹配失败");
                    }
                    toUserId = appUser1.getId();
                }
            }
            if (toUserId == 0 || toUserId == null) {
                return this.errorJSON("匹配失败");
            }
            AppUser toUser = appUserService.get(toUserId);

            AppSpouseClerk appSpouseClerk = appSpouseClerkService.randomGet(appUser.getSex());
            AppSpouseClerk appSpouseClerk1 = appSpouseClerkService.randomGet(toUser.getSex());
            if (appSpouseClerk == null || appSpouseClerk1 == null) {
                return this.errorJSON("匹配失败");
            }
            appSpouseClerk.setUserPic(appUser.getPic());
            appSpouseClerk.setUserId(appUser.getId());
            appSpouseClerk.setNick(appUser.getNick());
            appSpouseClerk.setTxCode(appUser.getTengxuncode());
            appSpouseClerk1.setToUserPic(toUser.getPic());
            appSpouseClerk1.setUserId(toUser.getId());
            appSpouseClerk1.setNick(toUser.getNick());
            appSpouseClerk1.setTxCode(toUser.getTengxuncode());

            /**************************夫妻匹配赠送心动礼物开始*****************************/
            if (appUser.getDiamonds().compareTo(BigDecimal.ZERO) == 0) {
                return this.errorJSON("钻石余额不足");
            }
            AppGift gift = appGiftService.randomGift(appUser.getDiamonds());
            BigDecimal money = new BigDecimal(String.valueOf((gift.getGoldmoney() * 1)));
            //判断金额是否够
            if (gift.getGoumaifangshi() == Constants.goumaifangshi_zuanshi) {
                //钻石
                if (money.compareTo(appUser.getDiamonds()) > 0) {
                    return this.errorJSON("钻石数量不足");
                }
            } else if (gift.getGoumaifangshi() == Constants.goumaifangshi_jinbi) {
                //金币
                if (money.compareTo(appUser.getJinbi()) > 0) {
                    return this.errorJSON("金币数量不足");
                }
            } else {
                return errorJSON("礼物类型错误");
            }
            boolean flag = appGiftService.spouseMatchUserGift(toUser, appUser, money, gift);
            Random random = new Random();
            if (flag) {
                //心动赠送礼物成功后存入redis此次匹配的用户，并返回匹配的信息
                redisUtil.set(RedisKeys.spouseMatch + appUser.getId(), toUser.getId(), 600);
                AppSpouseDto appSpouseDto = new AppSpouseDto();
                appSpouseDto.setUserSpouse(appSpouseClerk);
                appSpouseDto.setToUserSpouse(appSpouseClerk1);
                String format = String.format("%.2f", Math.random() * (100 - 85) + 85);
                appSpouseDto.setIndexNumber(format);
                return this.sucessJSON(appSpouseDto, "匹配成功");
            }
            /**************************夫妻匹配赠送心动礼物结束*****************************/
            return this.errorJSON("匹配失败");
        } catch (Exception e) {
            logger.error("夫妻相匹配异常：", e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }


}
